<html>
    <head>
        <!-- meta name="viewport" content="initial-scale=1.0, user-scalable=no" / -->
        <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
        <title>Tracking the Salvadorian Community</title>
        
        <!-- API links to Google Maps v3 and ArcGIS -->
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
		<script type="text/javascript" src="js/testarc.js"></script>
		<!--
		<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn-history/r172/trunk/arcgislink/src/arcgislink.js"></script>
		-->
		<!-- jquery -->
        <link rel="stylesheet" href="js/themes/base/jquery.ui.all.css"> 
        <script src="js/jquery-1.4.4.js"></script> 
        <script src="js/ui/jquery.ui.core.js"></script> 
        <script src="js/ui/jquery.ui.widget.js"></script> 
        <script src="js/ui/jquery.ui.mouse.js"></script> 
        <script src="js/ui/jquery.ui.draggable.js"></script> 
        <script src="js/ui/jquery.ui.button.js"></script> 

        <script> 
			
			$(function() {
				$( "#es_radio" ).buttonset();
				$( "#us_radio" ).buttonset();
			});
        </script>

    
        <!-- css -->
        <style type="text/css">
        #draggable, #draggable2 { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
        #draggable p { cursor: move; }
		td {
			font-size:10px;
			color:white;
		}
		h1 { font-size:20px; color:white; font-family:"Times New Roman", Times, serif ; padding:10px;margin:0px;}
		html { height: 100% }
		body { height: 100%; margin: 0px; padding: 0px }
		p {color:gray;font-size:12px; padding:10px;}
		#map1 { height: 100% }
		.resultsbar {background:#222; padding:4px;}
		.highlightedrow {background:#111;}
		.row {background:black;}
		
		.rounded-corners {
			-moz-border-radius: 10px;
			-webkit-border-radius: 10px;
			-khtml-border-radius: 10px;
			border-radius: 10px;
		}
		</style>
        
        <script type="text/javascript">



		/*
		
			For Debuggin
			
		*/
		
		function dump(arr,level) {
			var dumped_text = "";
			if(!level) level = 0;
			
			//The padding given at the beginning of the line.
			var level_padding = "";
			for(var j=0;j<level+1;j++) level_padding += "    ";
			
			if(typeof(arr) == 'object') { //Array/Hashes/Objects 
				for(var item in arr) {
					var value = arr[item];
					
					if(typeof(value) == 'object') { //If it is an array,
						dumped_text += level_padding + "'" + item + "' ...\n";
						dumped_text += dump(value,level+1);
					} else {
						dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
					}
				}
			} else { //Stings/Chars/Numbers etc.
				dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
			}
			return dumped_text;
		}
		
		/*
		
			Get mouse position for popup div
			
		*/
		jQuery(document).ready(function(){
		   $(document).mousemove(function(e){
			  $('#label1').css('left', e.pageX+5);
			  $('#label1').css('top', e.pageY-50);
		   }); 
		})

		/*
		
			Styles for map elements
			
		*/
		
		//hover style
		var hStyle = {
		  fillColor: '#883333',
		  fillOpacity: 0.35,
		  strokeColor: '#FF0000',
		  strokeWeight: 3,
		  zIndex: 100,
		  strokeOpacity: 1            
		};
		
		//normal style
		var style = {
		  fillColor: '#333388',
		  fillOpacity: 0.35,
		  strokeColor: '#FFFFFF',
		  strokeWeight: 1,
		  strokeOpacity: 1,
		  zIndex: 0
		};
		
		//alternative style
		var style2 = {
		  fillColor: '#FF0000',
		  fillOpacity: 0.35,
		  strokeColor: '#FFFFFF',
		  strokeWeight: 1,
		  strokeOpacity: 1,
		  zIndex: 0
		};
		
		
		/*
		
			Variable List
			
		*/
		
		var circle = [];
		var circledata = [];
		var map;
		var map2;
		var g;
		var highlighted = null;
		var iw = null;
		var es_id;
		var geolevel = "state";
		var es_geolevel = "Departamento";
		var us_geolevel = "";
		var es_id_field;
		var selectedmunicipio;
		var selectedmunicipioid;
		var es_poly = []; //El Salavodorean polygons
		var map2_layer ; //for spatial search
		var searchresults = [];

		/*
		
			Drawing Circle Functions
			
		*/		
		function clearCircles() {
			if (circle) {
			//alert('not clearing?');
				for (i in circle) {
					circle[i].setMap(null);
				}
			}
		}
			
		function clearPolys() {
			if (es_poly) {
			//alert('not clearing?');
				for (i in es_poly) {
					es_poly[i].setMap(null);
				}
			}
		}
						
		function randOrd(){
			return (Math.round(Math.random())-0.5); 
		}
			
		function drawboxes(count1,count2) {
			if (es_geolevel == "El Salvador")
			{
				personperbox = 100;
			}
			else if (es_geolevel == "Departamento")
			{
				personperbox = 50;
			}
			else if (es_geolevel == "Municipio")
			{
				personperbox = 10;
			}

			var numberofboxes = count1/personperbox;
			var boxeshtml = '';
			for (var i=0, c=numberofboxes; i < c; i++) {
				boxeshtml += '<span style="width:5px; height:5px; background: blue; float:left;border:1px solid black;"></span>';
				//boxeshtml += '<img src="images/red_box.jpg">';
			}
			if (count2)
			{
				var numberofboxes = count2/personperbox;
				for (var i=0, c=numberofboxes; i < c; i++) {
					boxeshtml += '<span style="width:5px; height:5px; background: red; float:left;border:1px solid black;"></span>';
					//boxeshtml += '<img src="images/red_box.jpg">';
				}
			}				
			return boxeshtml;
		}
		
		function drawpie(data, labels)
		{
			var total = 0;
			$.each(data,function() {
				total += this;
			});
			var piedata = '';
			var count = 1;
			$.each(data,function() {
				thisdata = Math.round(this/total*100);
				piedata += thisdata;
				if (count != data.length)
				{
					piedata += ',';
				}
				count = count + 1;
			});
			var pielabels = '';
			var count = 1;
			$.each(labels,function() {
				pielabels += this;
				if (count != data.length)
				{
					pielabels += '|';
				}
				count = count + 1;
			});

			var piehtml;
			piehtml = '<img src="http://chart.apis.google.com/chart?chf=bg,s,000000&chxs=0,EFEFEF,9&chxt=x&chs=180x65&cht=p&chco=0000FF,E21212&chd=t:'+piedata+'&chdlp=l&chl='+pielabels+'" width="180" height="65" alt="" /><br>';
			
			return piehtml;
		}
		
		function drawbar(count1,count2,count3)
		{
			total = count1+count2+count3;
			bar1 = Math.round(count1/total*100);
			bar2 = Math.round(count2/total*100);
			bar3 = Math.round(count3/total*100);
			var barhtml;
			
			barhtml = '<img src="http://chart.apis.google.com/chart?chxl=0:|under+17|18-64|65+and+up&chxp=0,1,3,5&chxr=0,0,6&chxt=x&chbh=a&chs=200x85&cht=bvg&chco=A2C180,3D7930,FF9900&chd=t:'+bar1+'|'+bar2+'|'+bar3+'&chtt=Vertical+bar+chart" width="200" height="85" alt="Vertical bar chart" />';
			
			return barhtml;
		}
		
		var listitems = [];
		var listmigranttotal = [];
		

		//get count
		function getCount(i,id,migranttotal)
		{
			
			// get json for to get total immigrants from this ES geography to the entire US
			if (es_geolevel == 'Departamento')
			{
				var jsonurl_count2us = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/10/query?where=ID_1+%3D+" + id + "&outFields=Migrant_Total&f=json&callback=?";
			}
			else if (es_geolevel == 'Municipio')
			{
				var jsonurl_count2us = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/11/query?where=ID_2+%3D+" + id + "&outFields=Migrant_Total&f=json&callback=?";
			}
			else if (es_geolevel == 'El Salvador')
			{
				var jsonurl_count2us = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/15/query?where=1+%3D+1&outFields=Migrant_Total&f=json&callback=?";
			}
			var totalmigrants2us;
			
			$.getJSON(jsonurl_count2us, function(data) {
				totalmigrants2us = data.features[0].attributes.Migrant_Total;
				percent = Math.round(migranttotal/totalmigrants2us*100);
				display = migranttotal + '/' + totalmigrants2us + ' (' + percent + '%)';
				document.getElementById("count"+i).innerHTML = display;
			});
		}
		
		function hiderow(id)
		{
			//alert('here');
			$('.'+id).slideToggle('slow');
		}


		function redrawcircles(es_id,es_name,us_geo)
		{
			us_geolevel=us_geo;
			drawcircles(es_id,es_name, us_geo);
		}

		/*
		
			Draw Circles 
			
		*/
		function drawcircles(es_id, featurename,us_geo) {
			
			if (us_geo != null)
			{
				us_geolevel = us_geo;
			}
			
			//clear existing circles
			clearCircles();
			
			//clear list items
			listitems.length = 0;
			listmigranttotal.length = 0;
			
			SouthWestLat = map.getBounds().getSouthWest().lat();
			SouthWestLon = map.getBounds().getSouthWest().lng();
			NorthEastLat = map.getBounds().getNorthEast().lat();
			NorthEastLon = map.getBounds().getNorthEast().lng();
						
			// If zoomed in, grab zipcode data, if not, county
			if (us_geolevel == "Zip")
			{
				geoname = "zipcodes";
				if (es_geolevel == "Departamento")
				{
					layerid = 9;
					es_id_field = "ID_1";
					wherequery = "where=" + es_id_field + "+%3D+" + es_id + "+AND+Migrant_Total+>+10";

				}
				else if (es_geolevel == "Municipio")
				{
					layerid = 14;
					es_id_field = "ID_2";
					wherequery = "where=" + es_id_field + "+%3D+" + es_id + "+AND+Migrant_Total+>+10";
				}
				else if (es_geolevel == "El Salvador")
				{
					layerid = 18;
					es_id_field = "SV_Name";
					wherequery = "where=Migrant_Total+>+10";
				}

				//Add bouding coordinates to query 
				wherequery_bounds = wherequery;
				/*
				wherequery_bounds += "+AND+USZip_Lat+>+" + SouthWestLat;
				wherequery_bounds += "+AND+USZip_Lat+<+" + NorthEastLat;
				wherequery_bounds += "+AND+USZip_Lon+>+" + SouthWestLon;
				wherequery_bounds += "+AND+USZip_Lon+<+" + NorthEastLon;
				*/
			}
			else if (us_geolevel == "County")
			{
				geoname = "counties";
				if (es_geolevel == "Departamento")
				{
					layerid = 7;
					es_id_field = "ID_1";
					wherequery = "where=" + es_id_field + "+%3D+" + es_id + "+AND+Migrant_Total+>+10";

				}
				else if (es_geolevel == "Municipio")
				{
					layerid = 13;
					es_id_field = "ID_2";
					wherequery = "where=" + es_id_field + "+%3D+" + es_id + "+AND+Migrant_Total+>+10";
				}
				else if (es_geolevel == "El Salvador")
				{
					layerid = 17;
					es_id_field = "SV_Name";
					wherequery = "where=Migrant_Total+>+10";
				}
				
				//Add bouding coordinates to query 
				wherequery_bounds = wherequery;
				/*
				wherequery_bounds += "+AND+USCnty_Lat+>+" + SouthWestLat;
				wherequery_bounds += "+AND+USCnty_Lat+<+" + NorthEastLat;
				wherequery_bounds += "+AND+USCnty_lon+>+" + SouthWestLon;
				wherequery_bounds += "+AND+USCnty_lon+<+" + NorthEastLon;
				*/	
			}
			

			else
			{
				geoname = "states";
				if (es_geolevel == "Departamento")
				{
					layerid = 8;
					layerid2us = 10;
					es_id_field = "ID_1";
					wherequery = "where=" + es_id_field + "+%3D+" + es_id + "+AND+Migrant_Total+>+10";

				}
				else if (es_geolevel == "Municipio")
				{
					layerid = 12;
					layerid2us = 11;
					es_id_field = "ID_2";
					wherequery = "where=" + es_id_field + "+%3D+" + es_id + "+AND+Migrant_Total+>+10";
				}
				else if (es_geolevel == "El Salvador")
				{
					layerid = 16;
					layerid2us = 15;
					es_id_field = "SV_Name";
					wherequery = "where=Migrant_Total+>+10";
				}
				
				//Add bouding coordinates to query 
				wherequery_bounds = wherequery;
				/*
				wherequery_bounds += "+AND+USSt_Lat+>+" + SouthWestLat;
				wherequery_bounds += "+AND+USSt_Lat+<+" + NorthEastLat;
				wherequery_bounds += "+AND+USSt_lon+<+" + NorthEastLon;
				wherequery_bounds += "+AND+USSt_lon+>+" + SouthWestLon;
				*/
			}
			
			// fade the data panel in
			$('#data1').fadeIn();
			
			// get json for to get total immigrants from this ES geography to the entire US
			var jsonurl_count2us = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/10/query?where=ID_1+%3D+" + es_id + "&outFields=Migrant_Total&f=json&callback=?";
			
			var totalmigrants2us;
			
			$.getJSON(jsonurl_count2us, function(data) {
				totalmigrants2us = data.features[0].attributes.Migrant_Total;
			});
			
			
			
			// get json for count
			var jsonurl_count = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/" + layerid + "/query?" + wherequery + "&returnGeometry=false&returnCountOnly=true&f=pjson&callback=?";
			
			var totalfeaturesfound;
			
			$.getJSON(jsonurl_count, function(data) {
				 totalfeaturesfound = data.count;
			});

			// get json
			var jsonurl = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/" + layerid + "/query?" + wherequery_bounds + "&returnGeometry=true&outFields=*&f=pjson&callback=?";

			//alert(jsonurl);
			$.getJSON(jsonurl, function(data) {
				
				
				// get json for to get total immigrants from this ES geography to the entire US
				var jsonurl_count2us = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/10/query?where=ID_1+%3D+" + es_id + "&outFields=Migrant_Total&f=json&callback=?";
				
				var totalmigrants2us;
				
				document.getElementById("data1").innerHTML = 'Migrants from<h1>' + featurename + '</h1>';
				document.getElementById("data1").innerHTML += '';
				
               	document.getElementById("data1").innerHTML += '';


				
				document.getElementById("data1").innerHTML += '<div class="resultsbar" id="resultsbar" style="height:20px;">' +totalfeaturesfound + ' ' + geoname + ' found | <span id="inviewcount" style="color:pink;">0</span> in view <a href="javascript:void(0);" onclick="hiderow(\'chartrow\')"><img src="http://cdn1.iconfinder.com/data/icons/Futurosoft%20Icons%200.5.2/16x16/apps/taskbar.png" style="float:right;padding-right:10px;"> <img src="http://cdn1.iconfinder.com/data/icons/IMPRESSIONS/business/png/16/pie_chart.png" style="float:right;padding-right:10px;"></a></div>';
				
				// sort the results array by migrant count
				data.features.sort(function(a,b){return parseFloat(a.attributes.Migrant_Total - b.attributes.Migrant_Total)}) //Array now becomes [7, 8, 25, 41]
				data.features.reverse();
				
				var count = 0;
				
				for (var i=0, c=data.features.length; i<c; i++) {
					// draw only if it's in bounds
					var bounds = map.getBounds();
					

					if (us_geolevel == "Zip")
					{
						var thiscenter = new google.maps.LatLng(data.features[i].attributes.USZip_Lat,data.features[i].attributes.USZip_Lon);						
					}
					else if (us_geolevel == "County")
					{
						var thiscenter = new google.maps.LatLng(data.features[i].attributes.USCnty_Lat,data.features[i].attributes.USCnty_lon);						
					}
					else
					{
						var thiscenter = new google.maps.LatLng(data.features[i].attributes.USSt_Lat,data.features[i].attributes.USSt_lon);						
					}


					if (bounds.contains(thiscenter) == true)
					{
						count = count + 1;
						var migrantcount = data.features[i].attributes.Migrant_Total;
						
						// this determines the circle size factor (ie, all circles are sized based on a factor of this number)
						var zoombase = 500;
						
						//show zips or counties depending on zoom level
						if (us_geolevel == "Zip")
						{
							var displayname = "Zipcode " + data.features[i].attributes.USZip_Name + ", " +  data.features[i].attributes.STATE;
							zoomfactor = zoombase/Math.pow(2,map.getZoom())*20;

							if (es_geolevel == "Departamento")
							{
								circlesize = migrantcount * zoomfactor;
							}
							else if (es_geolevel == "Municipio")
							{
								circlesize = migrantcount * zoomfactor;
							}
							else if (es_geolevel == "El Salvador")
							{
								circlesize = migrantcount * zoomfactor/10;
							}
						}
						else if (us_geolevel == "County")
						{
							var displayname = data.features[i].attributes.USCounty_Name + ' COUNTY, '+ data.features[i].attributes.USState_Name;
							zoomfactor = zoombase/Math.pow(2,map.getZoom())*4;
							if (es_geolevel == "Departamento")
							{
								circlesize = migrantcount * zoomfactor;
							}
							else if (es_geolevel == "Municipio")
							{
								circlesize = migrantcount * zoomfactor;
							}
							else if (es_geolevel == "El Salvador")
							{
								circlesize = migrantcount * zoomfactor/10;
							}
						}
						else
						{
							var displayname = 'State: ' + data.features[i].attributes.USState_Name;
							zoomfactor = zoombase/Math.pow(2,map.getZoom());
							if (es_geolevel == "Departamento")
							{
								circlesize = migrantcount * zoomfactor;
							}
							else if (es_geolevel == "Municipio")
							{
								circlesize = migrantcount * zoomfactor;
							}
							else if (es_geolevel == "El Salvador")
							{
								circlesize = migrantcount * zoomfactor/10;
							}
						}

						var thiscircle = new google.maps.Circle(
						{
							center: thiscenter,
							strokeColor: "#FF0000",
							strokeOpacity: 0.8,
							strokeWeight: 4,
							fillColor: "#FF0000",
							fillOpacity: 0.2,
							radius: circlesize
						});
						
						thiscircle.setMap(map);
						thiscircledata = '<strong>' + displayname + '</strong><br>Born in ' + featurename + ': ' + migrantcount;
						circle[i] = thiscircle;
						circledata.push(thiscircledata); 
						//showcircledatainlabel(thiscircle,thiscircledata);
						showcircledatainlabel(i,thiscircledata);
						//circle.push(thiscircle);

						// populate the data panel
						document.getElementById("inviewcount").innerHTML = count;
						migrant_total = data.features[i].attributes.Migrant_Total;
						
						var thislistitem = '<div id="listrow" class"listrow" onMouseOver="popup(\'' + data.features[i].attributes.Migrant_Male + ' males<br>' + data.features[i].attributes.Migrant_Female + ' females\');this.className=\'highlightedrow\';highlightcircle('+i+')" onMouseOut="popup_off();this.className=\'row\';dehighlightcircle('+i+')"><table width=100% ><tr><td valign="top" align="right" width=20>' + count + '</td><td valign="top">' + displayname + '</td><td valign="top" align="right" width=50 id="count'+(count-1)+'"></td></tr><tr class="chartrow" style="display:none"><td></td><td colspan=2>' + drawpie([data.features[i].attributes.Migrant_Male,data.features[i].attributes.Migrant_Female],['male','female']) + drawpie([data.features[i].attributes.Migrant_0_17,data.features[i].attributes.Migrant_18_64,data.features[i].attributes.Migrant_65_up],['age 0-17','18-64','65 and up']) + '</td></tr></table></div>';	
						
						listmigranttotal.push(migrant_total);
						listitems.push(thislistitem);

					}
					
					// exit loop when it reaches 50 - for optimization
					if (count > 49)
					{
						break;
					}
				}
				$("#progressbar").fadeOut();
				
				if (count > 10)
				{
					drawlistitems(0,10,es_id);
				}
				else
				{
					drawlistitems(0,data.features.length,es_id);
				}
				



			});
		}
		
		function popup(content)
		{
			$('#label1').css('padding','5px');
			document.getElementById("label1").innerHTML = content;
		}
		
		function popup_off()
		{
			$('#label1').css('padding','0px');
			document.getElementById("label1").innerHTML = '';
		}
		
		function highlightcircle(i)
		{
			circle[i].setOptions({ fillColor: "#0000FF",strokeColor:"#0000FF" });
		}
		
		function dehighlightcircle(i)
		{
			circle[i].setOptions({ fillColor: "#FF0000",strokeColor:"#FF0000" });
		}
		
		
		function drawlistitems(start, end, es_id)
		{
			//alert(end);
			for (var i = start, c =end; i < c; i++) {
				document.getElementById("data1").innerHTML += listitems[i];
				
				getCount(i,es_id,listmigranttotal[i]);
				
				
			}
			// show "more" if only showing top 10
			if (end == 10)
			{
				document.getElementById("data1").innerHTML += '<div class="resultsbar" id="more" style="cursor:pointer;">more...</div>';
				
				$("#more").click(function(){ 
					
					$("#more").html('loading...<img src="images/pbar-ani.gif" width=50 height=10>');
					setTimeout("drawlistitems(10,listitems.length, es_id)",100); 
					
					} );
			}
			else
			{
				$("#more").hide();
			}
		}
		
		function showcircledatainlabel(i,content) {		

			google.maps.event.addListener(circle[i], 'mouseover', function() {
					$('#label1').css('padding','5px');
					document.getElementById("label1").innerHTML = content;
				});
			google.maps.event.addListener(circle[i], 'click', function() {
					map.panTo(circle[i].getCenter());

					if (map.getZoom() < 8 && map.getZoom() > 5)
					{
						us_geolevel = "Zip";
						map.setZoom(9);
					}
					else if (map.getZoom() < 6)
					{
						us_geolevel = "County";
						map.setZoom(6);
					}

					drawcircles(this_es_id,featurename, us_geolevel);		
				});
			google.maps.event.addListener(circle[i], 'mouseout', function() {
					$('#label1').css('padding','0px');
					document.getElementById("label1").innerHTML = '';
				});
		}


		/*
		
			Map 2
			
		*/
		function init_map2(id){
			
			

			// set the El Salvador geo level
			if (id == 4)
			{
				es_geolevel = "Municipio";
				

				$('#es_dropdown').html('');
				
				jsonurl = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/4/query?where=1%3D1&returnGeometry=false&outFields=NAME_1,+NAME_2&f=pjson&callback=?";
				
				$('#es_dropdown').append('<select id="muni_dropdown"></select>');

				$.getJSON(jsonurl, function(data) {
					for (var i=0, c=data.features.length; i<c; i++) 
					{
						
						$('#muni_dropdown').append('<option value="one">'+data.features[i].attributes.NAME_1+'-'+data.features[i].attributes.NAME_2+'</option>');
					}
				});


			}
			else if (id == 5)
			{
				es_geolevel = "Departamento";
				
				$('#es_dropdown').html('');
				
				jsonurl = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer/5/query?where=1%3D1&&returnGeometry=false&outFields=Name_1,ID_1&f=pjson&callback=?";
				
				$('#es_dropdown').append('<select id="muni_dropdown"></select>');

				$.getJSON(jsonurl, function(data) {
					for (var i=0, c=data.features.length; i<c; i++) 
					{
						
						$('#muni_dropdown').append('<option value="'+data.features[i].attributes.ID_1+'">'+data.features[i].attributes.NAME_1+'</option>');
					}
				});
				$('#es_dropdown').change(function(){
					var val = $(this).find('option:selected').val();
					var name = $(this).find('option:selected').text();
					$('#data1').html("");
					$('#data1').fadeOut();
					$('#arrow').fadeOut();
					$("#progressbar").fadeIn()
					drawcircles(val,name, us_geolevel);
					
					//document.getElementById("label1selected").innerHTML = featurename;
					selectedmunicipioid = val;
					selectedmunicipio = name;



				});

			}
			else if (id == 6)
			{
				es_geolevel = "El Salvador";

				$('#es_dropdown').html('');
				
			}
			
			
			clearPolys();
			//var map2_url = "http://whippet.ats.ucla.edu/ArcGIS/rest/services/NAID/NAID/MapServer";
			//var map2_url = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/es_base/MapServer";
			var map2_url = "http://akbash.ats.ucla.edu:8399/arcgis/rest/services/NAID/data/MapServer";
			
			//var map2_queryurl = 'http://akbash.ats.ucla.edu:8399/arcgis/rest/services/es_base/MapServer/1/query?text=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=1%3D1&time=&returnCountOnly=false&returnIdsOnly=false&returnGeometry=true&maxAllowableOffset=&outSR=&outFields=ID_2,NAME_2,NAME_1,NAME_0&f=pjson&callback=?';
			
			
			//$.getJSON(map2_queryurl, function(data) { map2_processResultSet(data) });

			
			
			map2_layer = new gmaps.ags.Layer(map2_url + '/' + id);
			var map2_params = {
				returnGeometry: true,
				where: "1=1",
				overlayOptions: style
			};
			map2_layer.query(map2_params, map2_processResultSet);
			

		}
		
		function map2_processResultSet(rs) {
			var fs = rs.features;

			for (var i = 0, c = fs.length; i < c; i++) {
					
				map2_setupFeature(fs[i],i);
				$("#progressbar").fadeOut();
			}
		}

		function map2_setupFeature(feat,i) {
			var a = feat.attributes;
			
			if (es_geolevel == "Departamento")
			{
				var this_es_id = a['ID_1']; //ID_1 for departamento, ID_2 for municipio
				var featurename = a['NAME_1'];
			}
			else if (es_geolevel == "Municipio")
			{
				var this_es_id = a['ID_2']; //ID_1 for departamento, ID_2 for municipio
				var featurename = a['NAME_2'] + ', ' + a['NAME_1'];
			}
			else if (es_geolevel == "El Salvador")
			{
				var this_es_id = a['NAME_FAO']; //ID_1 for departamento, ID_2 for municipio
				var featurename = "El Salvador";
			}
			es_id = this_es_id;
			var html = "<div id='iwdiv' style='font-size:12px'><b>" + a['NAME_0'] + "</b><hr/>" +
			"<b>2000 Population: </b>" +
			a['NAME_1'] +
			"<br/>" +
			a['NAME_2'] +
			"<br/>" +
			'</div>';
				//document.getElementById("debug").innerHTML += dump(html);
			

			es_poly[i] = feat.geometry[0];//V3 supports multiple rings, so should have only 1 element
			
			var latlng = getPolyCenter(es_poly[i]);
			es_poly[i].setMap(map2);
			
			google.maps.event.addListener(es_poly[i], 'mouseover', function() {
				just_highlight(es_poly[i]);
				$('#label1').css('padding','5px');
				document.getElementById("label1").innerHTML = featurename;
				//drawcircles();
				//queryhighlight();
			});
			
			google.maps.event.addListener(es_poly[i], 'mouseout', function() {
				remove_highlight(es_poly[i]);
				$('#label1').css('padding','0px');
				document.getElementById("label1").innerHTML = '';
				//es_poly.setOptions(style);
				if (iw) {
					iw.close();
				}
			});
			
			google.maps.event.addListener(es_poly[i], 'click', function() {
				
				$('#data1').html("");
				$('#data1').fadeOut();
				$('#arrow').fadeOut();
				$("#progressbar").fadeIn()
				if (highlighted) {
					highlighted.setOptions(style);
				}
				map2_highlight(es_poly[i], html, latlng, map2);
				//alert("muniid = " + this_es_id);
				drawcircles(this_es_id,featurename, us_geolevel);
				
				//document.getElementById("label1selected").innerHTML = featurename;
				selectedmunicipioid = this_es_id;
				selectedmunicipio = featurename;
			});				
		}
		function just_highlight(g) {
			g.setOptions(hStyle);
		}
		
		function remove_highlight(g) {
			if (highlighted != g) {
				g.setOptions(style);
			}
		}
		
		function map2_highlight(g, html, latlng, mapid) {
			/*
			if (highlighted) {
				highlighted.setOptions(style);
			}
			*/
			//g.setOptions(hStyle);
			highlighted = g;
			
			if (!iw) {
				iw = new google.maps.InfoWindow({
				content: html,
				position: latlng,
				maxWidth: 240
				});
			} else {
				iw.setContent(html);
				iw.setPosition(latlng);
			}
			//iw.open(mapid);
		}

		//Function to get the center of the polygon
		function getPolyCenter(poly) {
			var paths, path, latlng;
			var lat = 0;
			var lng = 0;
			var c = 0;

			paths = poly.getPaths();
			for (var j = 0, jc = paths.getLength(); j < jc; j++) {
				path = paths.getAt(j);
				for (var k = 0, kc = path.getLength(); k < kc; k++) {
					latlng = path.getAt(k);
					lat += latlng.lat();
					lng += latlng.lng();
					c++;
				}
			}
			
			if (c > 0) {
				return new google.maps.LatLng(lat / c, lng / c);
			}
			return null;
		}
		
		/*
		
			Find
			
		*/
			function find(q) {
				removeSearchOverlays();
				var service = new gmaps.ags.MapService("http://whippet.ats.ucla.edu/ArcGIS/rest/services/NAID/NAID/MapServer");
				google.maps.event.addListener(gmaps.ags.Util, 'jsonpstart', function() {
					document.getElementById('busy').style.visibility = 'visible';
				});
				google.maps.event.addListener(gmaps.ags.Util, 'jsonpend', function() {
					document.getElementById('busy').style.visibility = 'hidden';
				});
				
				//var exact = document.getElementById('exact').checked;
				var params = {
					returnGeometry: true,
					searchText: q,
					//contains: !exact,
					layerIds: [1], // city, state
					searchFields: ["NAME_2"]
				};
				service.find(params, processFindResults);
			}

			function processFindResults(rs) {
				
				
				
				var fs = rs.results;
				
				
				
				if (fs.length == 0)
				{
					alert('0 results for your search');
				}
				for (var i = 0, c = fs.length; i < c; i++) {
					
					map2_setupFeature(fs[i],i);
					/*
					thisresult = fs[i].feature.geometry[0];
					thisresult.setMap(map2);
					searchresults.push(thisresult);
					*/
				}
			}
			
			function removeSearchOverlays() {
				if (searchresults) 
				{
					for (var i = 0; i < searchresults.length; i++) {
					searchresults[i].setMap(null);
				}
					searchresults.length = 0;
				}
			}
			


 		
		
		
		/*
		
		//initialize maps
		
		*/
		function init() {
			
			//map 1 (USA)
			var grayStyle = [
			  {
				featureType: "all",
				elementType: "all",
				stylers: [
				  //{ saturation: -99 },
				  { saturation: -50 }
				]
			  }
			];
			
			var map1Options = {
				zoom: 3,
				center: new google.maps.LatLng(40, -100),
				mapTypeId: google.maps.MapTypeId.SATELLITE,
				streetViewControl: false,
				mapTypeControl: true,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
					mapTypeIds: [
						google.maps.MapTypeId.ROADMAP, 
						google.maps.MapTypeId.SATELLITE, 
						google.maps.MapTypeId.TERRAIN, 
						'gray'
												],
					position: google.maps.ControlPosition.TOP
				},
				
				navigationControl: true,
				navigationControlOptions: {
					style: google.maps.NavigationControlStyle.SMALL
				}
			};
			
			//load map 1
			map = new google.maps.Map(document.getElementById("map1"), map1Options);
			
			var styledMap1Options = {
				name: "Black and White"
			}
			
			var grayMapType = new google.maps.StyledMapType(grayStyle, styledMap1Options);
			map.mapTypes.set('gray',grayMapType);
			//map.setMapTypeId('gray');
			
			var url = 'http://whippet.ats.ucla.edu/ArcGIS/rest/services/NAID/US_zip_base/MapServer';
			/*
			var agsType = new  gmaps.ags.MapType(url,{name:'ArcGIS'});
			map.mapTypes.set('arcgis', agsType);
			map.setMapTypeId('arcgis');
			*/

			var agsType = new  gmaps.ags.MapType(url,{name:'ArcGIS', opacity:0.5});
			map.overlayMapTypes.insertAt(0, agsType);

			
			//map 2 (El Salvador)
			var map2Options = {
				zoom: 7,
				center: new google.maps.LatLng(13.78, -88.9),
				mapTypeId: google.maps.MapTypeId.TERRAIN,
				streetViewControl: false,	
				mapTypeControl: false,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
				},
				navigationControl: true,
				navigationControlOptions: {
					style: google.maps.NavigationControlStyle.SMALL
				}
	
			};
			
			//load map 2
			map2 = new google.maps.Map(document.getElementById("map2"), map2Options);
			



			/*
				
				Map 1 (USA) Setup
				
			*/



			/*
			
			 	Map 2 (El Salvador)
			
			*/
			
			init_map2(5);
			
			
			google.maps.event.addListener(map, 'zoom_changed', function() {				
				drawcircles(selectedmunicipioid,selectedmunicipio, us_geolevel);
			});
			google.maps.event.addListener(map, 'dragend', function() {				
				drawcircles(selectedmunicipioid,selectedmunicipio, us_geolevel);
			});



		}
		
        </script>

    </head>

    <body bgcolor="silver" style="margin:0px; padding:0px;font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px;" onLoad="init()">
    <div align="left" id="map2container" style="position:absolute; background:black; padding:0 0px; width:25%; min-width:250px; height: 100%; overflow:auto; min-width:20%;opacity: 0.9;filter: alpha(opacity=90); z-index:10">
        <!-- Title -->
        <a href="javascript:void(0)" onClick="hiderow('minimap')"><img src="images/minimize.png" width="20" style="float:right;margin-top:10px;"></a>
        <h1>Where did they go?</h1>
        <h1>¿A dónde fueron?</h1>
        
        
        <div class="minimap">
            <p>Track the Salvadorean community by clicking on a region below:</p>
            <!-- -->

            <script  type='text/javascript'>
            $(document).ready(function(){					
                $("#radio4").click(function() {init_map2(6);$("#progressbar").fadeIn()});
                $("#radio5").click(function() {init_map2(5);$("#progressbar").fadeIn();populate_esdropdown("Departamento");});
                $("#radio6").click(function() {init_map2(4);$("#progressbar").fadeIn()});
            });
            </script>
            <form> 
                <div id="es_radio"> 
                    <input type="radio" id="radio4" name="radio" /><label for="radio4">El Salvador</label> 
                    <input type="radio" id="radio5" name="radio" checked="checked" /><label for="radio5">Departamento</label> 
                    <input type="radio" id="radio6" name="radio" /><label for="radio6">Municipio</label> 
                </div> 
            </form> 
            <div id="es_dropdown"></div>
            <div id="progressbar" style="position:absolute; top:200px; width:100%; background-image:url(images/pbar-ani.gif); height:15px; z-index:999; text-align:center; padding-top:3px;color:#333;">...loading...</div>
            <div id="map2" style="width:100%; height:200px;opacity:none;alpha(opacity=100);"></div>
            
            <!-- search
            <p>Search:<input id='q' type='text' size='20' value='San'/><input id='find' type='button' value='Find' onclick='find(document.getElementById("q").value)'/>
            <input id='exact' type='checkbox'>Exact match</p>
             -->
        </div>
        <div id="data1" style="display:none; background:black; overflow:auto; color:white; font-size:10px; padding:5px; text-align:left;"></div>
    
    
            <script  type='text/javascript'>
            $(document).ready(function(){					
                $("#radio1").click(function() {redrawcircles(selectedmunicipioid,selectedmunicipio,'State');});
                $("#radio2").click(function() {redrawcircles(selectedmunicipioid,selectedmunicipio,'County');});
                $("#radio3").click(function() {redrawcircles(selectedmunicipioid,selectedmunicipio,'Zip');});
            });
            </script>
    
    


    </div>

	<!-- Map -->
	<div id="map1" style="width:75%; height:100%; float:right;"></div>


        <div id="us_geo_buttons" style="height:10px; position:absolute; right:10; top:15;color:white; font-size:10px; padding:5px; text-align:right;">
            <form>
                <div id="us_radio">
                    <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">State</label>
                    <input type="radio" id="radio2" name="radio" /><label for="radio2">County</label>
                    <input type="radio" id="radio3" name="radio" /><label for="radio3">Zip</label>
                </div>
            </form>
        </div>
    
	<div id="label1" style="font-size:10px;position:absolute;  z-index:9999; font-size:12px; text-align:center; background: black; color:white;opacity:0.6;filter:alpha(opacity=60);"></div>


    </body>

</html>
